<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/2/5
 * Time: 12:57
 */
namespace app\api\common;
use think\Controller;
use think\Db;
use think\Exception;

class Goods extends Controller
{
    protected static $err_code = 0;

    /**
     *
     * @apiGroup Goods
     * @apiVersion 1.0.1
     * @apiDescription 全站商品搜索(已废除)
     * @api {post} /goods.goods_search 全站商品搜索(已废除)
     * @apiName Goods_goods_search
     * @apiParam {String} keyword 关键词
     * @apiParam {int} sort 排序(0.综合（最新），1.券后价(低到高)，2.券后价（高到低），3.券面额，4.销量，5.佣金比例)
     * @apiParam {int} price_min 最低价(券后价筛选，筛选大于等于所设置的券后价的商品 可不传)
     * @apiParam {int} price_max 最高价(券后价筛选，筛选小于等于所设置的券后价的商品 可不传)
     * @apiParam {int} page 页码（默认为1 ，条件改变时该参数可不传）
     *
     * @apiSuccess {int} code 结果码
     * @apiSuccess {String} msg 消息说明
     * @apiSuccess {Object} data
     * @apiSuccess {int} data.next_page  下一页页码
     * @apiSuccess {Object} data.data
     * @apiSuccess {int} data.data.itemid 淘宝商品id
     * @apiSuccess {String} data.data.itemtitle 宝贝标题
     * @apiSuccess {String} data.data.shorttitle 宝贝短标题
     * @apiSuccess {String} data.data.itemdesc  宝贝推荐语
     * @apiSuccess {float} data.data.itemprice 	在售价
     * @apiSuccess {int} data.data.itemsale 宝贝月销量
     * @apiSuccess {float} data.data.itemendprice 宝贝券后价
     * @apiSuccess {String} data.data.shoptype 店铺类型：天猫（B） 普通店铺（C）
     * @apiSuccess {float} data.data.couponmoney 优惠券金额
     * @apiSuccess {String} data.data.couponurl 优惠券链接
     * @apiSuccess {int} data.data.userid 店主的userid
     * @apiSuccess {String} data.data.sellernick 店铺掌柜名
     * @apiSuccessExample 成功示例
     *  HTTP/1.1 200 OK
     *  {
     *     code:200,
     *     msg:'success',
     *     data:{
     *         next_page:''
     *          data:{
                    ...
     *              }
     *	   }
     *  }
     *
     *  @apiError code 0 系统异常错误
     *  @apiError msg token已经过期
     *  @apiErrorExample {json} 失败示例
     *  HTTP/1.1 404 Not Found
     *  {
     *     code:0,
     *      msg:'失败或没有数据返回',
     *   }
     */

    public static function goods_search($param){
        if (!isset($param['keyword']) || empty($param['keyword'])){
            return ['data' => '', 'code' => 400001, 'msg' => '参数错误'];
        }
        if (!isset($param['page']) || empty($param['page'])){
            $param['page'] = 1;
        }
        try{
            $apikey = 'shen';
            $sort = 0;
            if (isset($param['sort']) && !empty($param['sort'])){
                $sort = $param['sort'];
            }
            $price_min = 0;
            $price_max = 0;
            if (isset($param['price_min']) && !empty($param['price_min'])){
                $price_min = $param['price_min'];
            }
            if (isset($param['price_max']) && !empty($param['price_max'])){
                $price_max = $param['price_max'];
            }
            if ( $price_min != 0 && $price_max != 0){
                $url = "http://v2.api.haodanku.com/get_keyword_items/apikey/".$apikey."/keyword/".$param['keyword']."/back/10/sort/".$sort."/cid/0/price_min/".$price_min."/price_max/".$price_max."min_id/".$param['page'];
            }else if ($price_min == 0 && $price_max != 0){
                $url = "http://v2.api.haodanku.com/get_keyword_items/apikey/".$apikey."/keyword/".$param['keyword']."/back/10/sort/".$sort."/cid/0/price_max/".$price_max."min_id/".$param['page'];
            }else if ($price_min != 0 && $price_max == 0){
                $url = "http://v2.api.haodanku.com/get_keyword_items/apikey/".$apikey."/keyword/".$param['keyword']."/back/10/sort/".$sort."/cid/0/price_min/".$price_min."min_id/".$param['page'];
            }else{
                $url = "http://v2.api.haodanku.com/get_keyword_items/apikey/".$apikey."/keyword/".$param['keyword']."/back/10/sort/".$sort."/cid/0/min_id/".$param['page'];
            }
            $data =cache(md5($url));
            if (empty($data)){
                $data = curl_request($url);
                cache(md5($url),$data);
            }
            if ($data['code'] == 1){
                $list_info['next_page'] = $data['min_id'];
                foreach ($data['data'] as $k=>$v){
                    $list_info['data'][$k]['itemid'] = $v['itemid'];
                    $list_info['data'][$k]['itemtitle'] = $v['itemtitle'];
                    $list_info['data'][$k]['shorttitle'] = $v['itemshorttitle'];
                    $list_info['data'][$k]['itemdesc'] = $v['itemdesc'];
                    $list_info['data'][$k]['itemprice'] = $v['itemprice'];
                    $list_info['data'][$k]['itemsale'] = $v['itemsale'];
                    $list_info['data'][$k]['itempic'] = $v['itempic'];
                    $list_info['data'][$k]['itemendprice'] = $v['itemendprice']; //券后价
                    $list_info['data'][$k]['shoptype'] = $v['shoptype'];
                    $list_info['data'][$k]['couponmoney'] = $v['couponmoney'];
                    $list_info['data'][$k]['couponurl'] = $v['couponurl'];
                    $list_info['data'][$k]['userid'] = $v['userid'];
                    $list_info['data'][$k]['sellernick'] = $v['sellernick'];
                }
            }else{
                self::$err_code = 0;
                throw new Exception($data['msg']);
            }
            return ['code'=>200,'msg'=>'SUCCESS','data'=>$list_info];


        }catch (Exception $e){
            return ['code' => self::$err_code, 'msg' => $e->getMessage()];
        }
    }

    /**
     *
     * @apiGroup Goods
     * @apiVersion 1.0.1
     * @apiDescription 全站商品搜索
     * @api {post} /goods.search 全站商品搜索
     * @apiName Goods_search
     * @apiParam {String} keyword 关键词
     * @apiParam {int} sort 排序(0.人气，1.券后价(低到高)，2.券后价（高到低），3.销量，4.最新)
     * @apiParam {int} page 页码（默认为1 ，data外面）
     *
     * @apiSuccess {int} code 结果码
     * @apiSuccess {String} msg 消息说明
     * @apiSuccess {Object} data
     * @apiSuccess {Object} data.total  总数
     * @apiSuccess {Object} data.per_page  每页数量
     * @apiSuccess {Object} data.current_page  当前页
     * @apiSuccess {Object} data.last_page  最后的页码
     * @apiSuccess {Object} data.data  商品数据
     * @apiSuccess {String} data.data.itemid 淘宝id
     * @apiSuccess {String} data.data.itemtitle 商品标题
     * @apiSuccess {String} data.data.itemprice 商品现价
     * @apiSuccess {String} data.data.itemendprice 商品券后价
     * @apiSuccess {String} data.data.itempic 商品图片
     * @apiSuccess {String} data.data.couponurl 优惠券链接
     * @apiSuccess {String} data.data.shoptype 店铺类型：天猫（B）C店（C）
     * @apiSuccess {int} data.data.itemsale 销量
     * @apiSuccessExample 成功示例
     *  HTTP/1.1 200 OK
     *  {
     *     code:200,
     *     msg:'success',
     *     data:{
     *         next_page:''
     *          data:{
    ...
     *              }
     *	   }
     *  }
     *
     *  @apiError code 0 系统异常错误
     *  @apiError msg token已经过期
     *  @apiErrorExample {json} 失败示例
     *  HTTP/1.1 404 Not Found
     *  {
     *     code:0,
     *      msg:'失败或没有数据返回',
     *   }
     */

    public static function search($param){
        if (!isset($param['keyword']) || empty($param['keyword'])){
            return ['data' => '', 'code' => 400001, 'msg' => '参数错误'];
        }
        try{
            if (isset($param['sort']) && $param['sort'] != ''){
                $sort = $param['sort'];
            }else{
                $sort = 0;
            }
            if ($sort == 0){
                $order_condition = 'todaysale desc';
            }else if ($sort == 1){
                $order_condition = 'itemendprice asc';
            }else if ($sort == 2){
                $order_condition = 'itemendprice desc';
            }else if($sort == 3){
                $order_condition = 'itemsale desc';
            }else{
                $order_condition = 'start_time desc';
            }
            $goods_list = Db::table('yf_items')->field('itemid,itemtitle,itemprice,itemendprice,itempic,couponurl,shoptype,itemsale')
                ->where(['itemtitle'=>['like',"%".$param['keyword']."%"]])
                ->where(['couponstarttime'=>['lt',time()],'couponendtime'=>['gt',time()],'start_time'=>['lt',time()],'end_time'=>['gt',time()]])
                ->order($order_condition)
                ->paginate('10');
            $goods_list = $goods_list->toArray();

            return ['code'=>200,'msg'=>'SUCCESS','data'=>$goods_list];


        }catch (Exception $e){
            return ['code' => self::$err_code, 'msg' => $e->getMessage()];
        }
    }

    /**
     *
     * @apiGroup Goods
     * @apiVersion 1.0.1
     * @apiDescription 基于淘宝全站商品搜索
     * @api {post} /goods.tbsearch 基于淘宝全站商品搜索
     * @apiName Goods_tbsearch
     * @apiParam {String} keyword 关键词
     * @apiParam {int} sort 排序(0.综合，1.销量,2有优惠券 3天猫)
     * @apiParam {int} page 页码（默认为1 ，data外面）
     *
     * @apiSuccess {int} code 结果码
     * @apiSuccess {String} msg 消息说明
     * @apiSuccess {Object} data
     * @apiSuccess {Object} data.total  总数
     * @apiSuccess {Object} data.per_page  每页数量
     * @apiSuccess {Object} data.current_page  当前页
     * @apiSuccess {Object} data.last_page  最后的页码
     * @apiSuccess {Object} data.data  商品数据
     * @apiSuccess {String} data.data.itemid 淘宝id
     * @apiSuccess {String} data.data.itemtitle 商品标题
     * @apiSuccess {String} data.data.itemprice 商品现价
     * @apiSuccess {String} data.data.itemendprice 商品券后价
     * @apiSuccess {String} data.data.itempic 商品图片
     * @apiSuccess {String} data.data.couponurl 优惠券链接
     * @apiSuccess {String} data.data.shoptype 店铺类型：天猫（B）C店（C）
     * @apiSuccess {int} data.data.itemsale 销量
     * @apiSuccess {int} data.data.couponstarttime 优惠券开始时间
     * @apiSuccess {int} data.data.couponendtime 优惠券结束时间
     * @apiSuccess {String} data.data.share_url 分享的链接
     * @apiSuccessExample 成功示例
     *  HTTP/1.1 200 OK
     *  {
     *     code:200,
     *     msg:'success',
     *     data:{
     *         next_page:''
     *          data:{
    ...
     *              }
     *	   }
     *  }
     *
     *  @apiError code 0 系统异常错误
     *  @apiError msg token已经过期
     *  @apiErrorExample {json} 失败示例
     *  HTTP/1.1 404 Not Found
     *  {
     *     code:0,
     *      msg:'失败或没有数据返回',
     *   }
     */


    public static function tbsearch($param)
    {

        $page = intval(input('page', 1)); //页码
        if (!isset($param['keyword']) || empty($param['keyword'])) {
            return ['data' => '', 'code' => 400001, 'msg' => '参数错误'];
        }
        try {
            $c = new \TopClient();
            $c->appkey = '24635648';//公司账号
            $c->secretKey = 'e3c6f335ca39011870018a730503de72'; //公司账号
            $req = new \TbkDgMaterialOptionalRequest();
            $req->setPageSize("20"); //页大小，默认20，1~100
            $req->setPageNo($page); //第几页，默认：１
            $req->setPlatform("1"); //链接形式：1：PC，2：无线，默认：１
            if ($param['sort'] == 1) { //销量
                $req->setIsTmall("false"); //是否商城商品，设置为true表示该商品是属于淘宝商城商品，设置为false或不设置表示不判断这个属性
                $req->setSort("total_sales_des"); //排序_des（降序），排序_asc（升序），销量（total_sales），淘客佣金比率（tk_rate）， 累计推广量（tk_total_sales），总支出佣金（tk_total_commi），价格（price）
            }elseif ($param['sort'] == 2){ //有优惠券
                $req->setIsTmall("false"); //是否商城商品，设置为true表示该商品是属于淘宝商城商品，设置为false或不设置表示不判断这个属性
                $req->setHasCoupon("true");
            }elseif ($param['sort'] == 3){ //天猫
                $req->setIsTmall("true"); //是否商城商品，设置为true表示该商品是属于淘宝商城商品，设置为false或不设置表示不判断这个属性
            }else{
                $req->setIsTmall("false"); //是否商城商品，设置为true表示该商品是属于淘宝商城商品，设置为false或不设置表示不判断这个属性
            }
            $req->setQ($param['keyword']); //查询词
            $req->setAdzoneId("126340444"); //	adzone_id公司
            $resp = $c->execute($req);
            $data = object_array($resp);
            $info = [];
            if (isset($data['sub_code']) && $data['sub_code'] == '50001'){
                $info['data'] = [];
                return ['code' => 200, 'msg' => 'SUCCESS', 'data' => $info];
            }
            $info['total'] = intval($data['total_results']);
            $info['per_page'] = 20;
            $info['current_page'] = $page;
            $info['last_page'] = intval(ceil($data['total_results'] / 20));
            if (!empty($data['result_list']['map_data'])) {
                if ($data['total_results'] == 1){
                    if (!empty($data['result_list']['map_data']['coupon_info'])) {
                        $t1 = mb_strpos($data['result_list']['map_data']['coupon_info'], '减');
                        $t2 = mb_strpos($data['result_list']['map_data']['coupon_info'], '元');
                        $info['data'][0]['itemendprice'] = strval($data['result_list']['map_data']['zk_final_price'] - mb_substr($data['result_list']['map_data']['coupon_info'], $t1 + 1, $t2 - $t1));
                        $info['data'][0]['couponmoney'] = mb_substr($data['result_list']['map_data']['coupon_info'], $t1 + 1, $t2 - $t1);
                        $info['data'][0]['couponurl'] = 'https://uland.taobao.com/coupon/edetail?activityId=' . $data['result_list']['map_data']['coupon_id'] . '&itemId=' . $data['result_list']['map_data']['num_iid'] . '&src=cd_cdll';
                        $info['data'][0]['couponstarttime'] = strtotime($data['result_list']['map_data']['coupon_start_time']);
                        $info['data'][0]['couponendtime'] = strtotime($data['result_list']['map_data']['coupon_end_time']);
                    }else{
                        $info['data'][0]['itemendprice'] = $data['result_list']['map_data']['zk_final_price'];
                        $info['data'][0]['couponurl'] = '';
                        $info['data'][0]['couponmoney'] = '';
                        $info['data'][0]['couponstarttime'] = '';
                        $info['data'][0]['couponendtime'] = '';
                    }
                    $info['data'][0]['itemid'] = $data['result_list']['map_data']['num_iid'];
                    $info['data'][0]['itemtitle'] = $data['result_list']['map_data']['title'];
                    $info['data'][0]['itemprice'] = $data['result_list']['map_data']['zk_final_price'];
                    $info['data'][0]['itempic'] = $data['result_list']['map_data']['pict_url'];
                    $info['data'][0]['shoptype'] = $data['result_list']['map_data']['user_type'] == 1 ? 'B' : 'C';
                    $info['data'][0]['itemsale'] = $data['result_list']['map_data']['volume'];
                    $info['data'][0]['share_url'] = '';
                }else{
                    foreach ($data['result_list']['map_data'] as $k => $v) {
                        if (!empty($v['coupon_info'])) {
                            $t1 = mb_strpos($v['coupon_info'], '减');
                            $t2 = mb_strpos($v['coupon_info'], '元');
                            $info['data'][$k]['itemendprice'] = strval($v['zk_final_price'] - mb_substr($v['coupon_info'], $t1 + 1, $t2 - $t1));
                            $info['data'][$k]['couponmoney'] = mb_substr($v['coupon_info'], $t1 + 1, $t2 - $t1);
                            $info['data'][$k]['couponurl'] = 'https://uland.taobao.com/coupon/edetail?activityId=' . $v['coupon_id'] . '&itemId=' . $v['num_iid'] . '&src=cd_cdll';
                            $info['data'][$k]['couponstarttime'] = strtotime($v['coupon_start_time']);
                            $info['data'][$k]['couponendtime'] = strtotime($v['coupon_end_time']);
                        }else{
                            $info['data'][$k]['itemendprice'] = $v['zk_final_price'];
                            $info['data'][$k]['couponurl'] = '';
                            $info['data'][$k]['couponmoney'] = '';
                            $info['data'][$k]['couponstarttime'] ='';
                            $info['data'][$k]['couponendtime'] = '';
                        }
                        $info['data'][$k]['itemid'] = $v['num_iid'];
                        $info['data'][$k]['itemtitle'] = $v['title'];
                        $info['data'][$k]['itemprice'] = $v['zk_final_price'];
                        $info['data'][$k]['itempic'] = $v['pict_url'];
                        $info['data'][$k]['shoptype'] = $v['user_type'] == 1 ? 'B' : 'C';
                        $info['data'][$k]['itemsale'] = intval($v['volume']);
                        $info['data'][$k]['share_url'] = '';
                    }
                }


            } else {
                $info['data'] = [];
            }
            return ['code' => 200, 'msg' => 'SUCCESS', 'data' => $info];

        } catch (Exception $e) {
            return ['code' => 0, 'msg' => $e->getMessage()];
        }
    }



    public static function tbsearchold($param)
    {

        $page = intval(input('page', 1)); //页码
        if (!isset($param['keyword']) || empty($param['keyword'])) {
            return ['data' => '', 'code' => 400001, 'msg' => '参数错误'];
        }
        $access_token = '';
        $tbauth = Db::table('yf_tbauth')->where(['taobao_user_id' => '642623368'])->find(); //查找出642623368的授权信息
        if (!empty($tbauth)) {
            if ($tbauth['token_endtime'] < time()) { //如果token已过期

                $result = tbrefresh(['refresh_token' => $tbauth['refresh_token'], 'taobao_user_id' => $tbauth['taobao_user_id'], 'id' => $tbauth['id']]);//刷新授权
                if ($result['code'] == 0) {
                    return ['data' => '', 'code' => 0, 'msg' => $result['msg']];
                }
                $access_token = $result['data'];
            } else {
                $access_token = $tbauth['access_token'];

            }
        } else {
            return ['data' => '', 'code' => 0, 'msg' => '授权失败，请在后台进行淘宝授权'];
        }

        try {
            $c = new \TopClient();
            $c->appkey = '24635648';//公司账号
            $c->secretKey = 'e3c6f335ca39011870018a730503de72'; //公司账号
            $req = new \TbkScMaterialOptionalRequest();
            $req->setPageSize("20"); //页大小，默认20，1~100
            $req->setPageNo($page); //第几页，默认：１
            $req->setPlatform("1"); //链接形式：1：PC，2：无线，默认：１
            $req->setStartTkRate("2000"); //淘客佣金比率下限，如：1234表示12.34%
            $req->setIsOverseas("false"); //是否海外商品，设置为true表示该商品是属于海外商品，设置为false或不设置表示不判断这个属性
            $req->setIsTmall("false"); //是否商城商品，设置为true表示该商品是属于淘宝商城商品，设置为false或不设置表示不判断这个属性
            if ($param['sort'] == '0') {
                $req->setSort("tk_total_sales_des");   //排序_des（降序），排序_asc（升序），销量（total_sales），淘客佣金比率（tk_rate）， 累计推广量（tk_total_sales），总支出佣金（tk_total_commi），价格（price）
            } elseif ($param['sort'] == 1) {
                $req->setSort("total_sales_desc");
            }
            $req->setQ($param['keyword']); //查询词
            $req->setAdzoneId("125494351"); //	adzone_id公司
            $req->setSiteId("35350242"); //site_id 公司
            $req->setHasCoupon("false"); //是否有优惠券，设置为true表示该商品有优惠券，设置为false或不设置表示不判断这个属性
            $resp = $c->execute($req, $access_token);  //公司的号
            $data = object_array($resp);
            $info = [];
            $info['total'] = intval($data['total_results']);
            $info['per_page'] = 20;
            $info['current_page'] = $page;
            $info['last_page'] = intval(ceil($data['total_results'] / 20));
            if (!empty($data['result_list']['map_data'])) {
                foreach ($data['result_list']['map_data'] as $k => $v) {
                    if (!empty($v['coupon_info'])) {
                        $t1 = mb_strpos($v['coupon_info'], '减');
                        $t2 = mb_strpos($v['coupon_info'], '元');
                        $info['data'][$k]['itemendprice'] = strval($v['zk_final_price'] - mb_substr($v['coupon_info'], $t1 + 1, $t2 - $t1));
                        $info['data'][$k]['couponurl'] = 'https://uland.taobao.com/coupon/edetail?activityId=' . $v['coupon_id'] . '&itemId=' . $v['num_iid'] . '&src=cd_cdll';
                    } else {
                        $info['data'][$k]['itemendprice'] = $v['zk_final_price'];
                        $info['data'][$k]['couponurl'] = '';
                    }
                    $info['data'][$k]['itemid'] = $v['num_iid'];
                    $info['data'][$k]['itemtitle'] = $v['title'];
                    $info['data'][$k]['itemprice'] = $v['zk_final_price'];
                    $info['data'][$k]['itempic'] = $v['pict_url'];
                    $info['data'][$k]['shoptype'] = $v['user_type'] == 1 ? 'B' : 'C';
                    $info['data'][$k]['itemsale'] = $v['volume'];
                }
            } else {
                $info['data'] = [];
            }
            return ['code' => 200, 'msg' => 'SUCCESS', 'data' => $info];

        } catch (Exception $e) {
            return ['code' => 200, 'msg' => 'SUCCESS', 'data' => $info];
        }
    }


    /**
     *
     * @apiGroup Goods
     * @apiVersion 1.0.1
     * @apiDescription 商品搜索（已废除）
     * @apiParam {String} keyword 关键词
     * @api {post} /goods.search2 商品搜索（已废除）
     * @apiName Goods_search2
     * @apiParam {int} page 页码（默认为1 ，写在data里面）
     *
     * @apiSuccess {int} code 结果码
     * @apiSuccess {String} msg 消息说明
     * @apiSuccess {Object} data
     * @apiSuccess {Object} data.results  淘宝客商品
     * @apiSuccess {Object} data.results.n_tbk_item  淘宝客商品
     * @apiSuccess {int} data.results.n_tbk_item.num_iid  商品ID
     * @apiSuccess {String} data.results.n_tbk_item.title  商品标题
     * @apiSuccess {String} data.results.n_tbk_item.pict_url  商品主图
     * @apiSuccess {Object} data.results.n_tbk_item.small_images  商品小图
     * @apiSuccess {Object} data.results.n_tbk_item.small_images.string  商品小图列表
     * @apiSuccess {String} data.results.n_tbk_item.reserve_price  商品一口价格
     * @apiSuccess {String} data.results.n_tbk_item.zk_final_price  商品折扣价格
     * @apiSuccess {int} data.results.n_tbk_item.user_type  卖家类型，0表示集市，1表示商城
     * @apiSuccess {String} data.results.n_tbk_item.provcity  宝贝所在地
     * @apiSuccess {String} data.results.n_tbk_item.item_url  商品地址
     * @apiSuccess {String} data.results.n_tbk_item.nick  卖家昵称
     * @apiSuccess {int} data.results.n_tbk_item.seller_id  卖家id
     * @apiSuccess {int} data.results.n_tbk_item.volume  30天销量
     * @apiSuccess {int} data.results.total_results  搜索到符合条件的结果总数
     * @apiSuccess {Object} data.results.request_id  请求的编号
     * @apiSuccessExample 成功示例
     *  HTTP/1.1 200 OK
     *  {
     *     code:200,
     *     msg:'success',
     *     data:{
    ...
     *	   }
     *  }
     *
     *  @apiError code 0 系统异常错误
     *  @apiError msg token已经过期
     *  @apiErrorExample {json} 失败示例
     *  HTTP/1.1 404 Not Found
     *  {
     *     code:0,
     *      msg:'失败或没有数据返回',
     *   }
     */
    public static function search2($param){
        if (!isset($param['keyword']) || empty($param['keyword'])){
            return ['data' => '', 'code' => 400001, 'msg' => '参数错误'];
        }
        if (!isset($param['page']) || empty($param['page'])){
            $page = (string)1;
        }else{
            $page = (string)$param['page'];
        }
        try{
            vendor('taobao.TopSdk');
            $c = new \TopClient();
            $c->appkey = '24636802';
            $c->secretKey = '490efd735c9cdf04aad19dc0d231517c';
            $req = new \TbkItemGetRequest;
            $req->setFields("num_iid,title,pict_url,small_images,reserve_price,zk_final_price,user_type,provcity,item_url,seller_id,volume,nick");
            $req->setQ($param['keyword']);
            $req->setSort("tk_total_sales_des");
            $req->setIsTmall("false");
            $req->setIsOverseas("false");
            $req->setPlatform("2");
            $req->setPageNo($page);
            $req->setPageSize("20");
            $resp = $c->execute($req);
            $resp = object_array($resp);
            return ['data' =>$resp, 'code' => 200, 'msg' => 'success'];
        }catch (Exception $e){
            return ['data' =>'', 'code' => self::$err_code, 'msg' => $e->getMessage()];
        }
    }

    /**
     *
     * @apiGroup Goods
     * @apiVersion 1.0.1
     * @apiDescription 热门搜索
     * @api {post} /goods.hot_words 热门搜索
     * @apiName Goods_hot_words
     *
     * @apiSuccess {int} code 结果码
     * @apiSuccess {String} msg 消息说明
     * @apiSuccess {Object} data
     * @apiSuccess {int} data.id 热词id
     * @apiSuccess {String} data.word 热词名称
     * @apiSuccess {int} data.add_time 添加时间
     * @apiSuccessExample 成功示例
     *  HTTP/1.1 200 OK
     *  {
     *     code:200,
     *     msg:'success',
     *     data:{
                ...
     *	   }
     *  }
     *
     *  @apiError code 0
     *  @apiError msg 系统异常错误
     *  @apiErrorExample {json} 失败示例
     *  HTTP/1.1 404 Not Found
     *  {
     *     code:0,
     *      msg:'失败或没有数据返回',
     *   }
     */
    public static function hot_words($param){
       try{
           if (empty($data)){
               $data = Db::table('yf_hot_word')->field('id,word,add_time')->order('sort desc')->select();
           }
           return ['code'=>200,'msg'=>'SUCCESS','data'=>$data];
       }catch (Exception $e){
           return ['code' => self::$err_code, 'msg' => $e->getMessage()];
       }
    }

    /**
     *
     * @apiGroup Goods
     * @apiVersion 1.0.1
     * @apiDescription 类别
     * @api {post} /goods.category 类别
     * @apiName Goods_category
     *
     * @apiSuccess {int} code 结果码
     * @apiSuccess {String} msg 消息说明
     * @apiSuccess {Object} data
     * @apiSuccess {int} data.id 类别id
     * @apiSuccess {String} data.name 类别名称
     * @apiSuccessExample 成功示例
     *  HTTP/1.1 200 OK
     *  {
     *     code:200,
     *     msg:'success',
     *     data:{
    ...
     *	   }
     *  }
     *
     *  @apiError code 0
     *  @apiError msg 系统异常错误
     *  @apiErrorExample {json} 失败示例
     *  HTTP/1.1 404 Not Found
     *  {
     *     code:0,
     *      msg:'失败或没有数据返回',
     *   }
     */
    public static function category(){
        try{
            $data = Db::table('yf_items_cate')->field('id,name')->where(['status'=>1,'parent_id'=>0])->order('sort asc')->select();
            return ['code'=>200,'msg'=>'SUCCESS','data'=>$data];
        }catch (Exception $e){
            return ['code' => self::$err_code, 'msg' => $e->getMessage()];
        }
    }

    /**
     *
     * @apiGroup Goods
     * @apiVersion 1.0.1
     * @apiDescription 获取指定类目下的二级类目
     * @api {post} /goods.category_v2 获取指定类别下的二级类目
     * @apiName Goods_category_v2
     * @apiParam {int} cat_id 类目id
     *
     * @apiSuccess {int} code 结果码
     * @apiSuccess {String} msg 消息说明
     * @apiSuccess {Object} data
     * @apiSuccess {int} data.id 类目id
     * @apiSuccess {String} data.name 类目名称
     * @apiSuccess {int} data.parent_id 父类id
     * @apiSuccess {String} data.icon 图标
     * @apiSuccess {Object} data.son 子类数据
     * @apiSuccess {int} data.son.id 类目id
     * @apiSuccess {String} data.son.name 类目名称
     * @apiSuccess {int} data.son.parent_id 父类id
     * @apiSuccess {String} data.son.icon 图标
     * @apiSuccessExample 成功示例
     *  HTTP/1.1 200 OK
     *  {
     *     code:200,
     *     msg:'success',
     *     data:{
    ...
     *	   }
     *  }
     *
     *  @apiError code 0
     *  @apiError msg 系统异常错误
     *  @apiErrorExample {json} 失败示例
     *  HTTP/1.1 404 Not Found
     *  {
     *     code:0,
     *      msg:'失败或没有数据返回',
     *   }
     */
    public static function category_v2($param){
        if (!isset($param['cat_id']) || empty($param['cat_id'])){
            return ['data' => '', 'code' => 400001, 'msg' => '参数错误'];
        }
        try{
            $data = Db::table('yf_items_cate')->field('id,name,parent_id,icon')->where(['status'=>1,'id'=>$param['cat_id']])->find();
            if (!empty($data)){
                if(!empty($data['icon'])){
                    $data['icon'] = get_img_url($data['icon']);
                }
            }
            $son = Db::table('yf_items_cate')->field('id,name,parent_id,icon')->where(['status'=>1,'parent_id'=>$param['cat_id']])->order('sort asc')->select();
            if (!empty($son)){
                foreach ($son as $k=>$v){
                    if(!empty($v['icon'])){
                        $son[$k]['icon'] = get_img_url($v['icon']);
                    }
                }
            }
            $data['son'] = $son;
            return ['code'=>200,'msg'=>'SUCCESS','data'=>$data];
        }catch (Exception $e){
            return ['code' => self::$err_code, 'msg' => $e->getMessage()];
        }
    }


    /**
     *
     * @apiGroup Goods
     * @apiVersion 1.0.1
     * @apiDescription 高佣转链获取优惠券
     * @api {post} /goods.ratesurl 高佣转链获取优惠券
     * @apiName Goods_ratesurl
     * @apiParam {int} itemid 商品淘宝id
     * @apiParam {int} agent_id 用户所属的代理商id（不传或者为空，默认为平台）
     *
     * @apiSuccess {int} code 结果码
     * @apiSuccess {String} msg 消息说明
     * @apiSuccess {Object} data
     * @apiSuccess {int} data.coupon_click_url 高佣优惠券链接(为空则直接跳转详情)
     * @apiSuccessExample 成功示例
     *  HTTP/1.1 200 OK
     *  {
     *     code:200,
     *     msg:'success',
     *     data:{
    ...
     *	   }
     *  }
     *
     *  @apiError code 0
     *  @apiError msg 系统异常错误
     *  @apiErrorExample {json} 失败示例
     *  HTTP/1.1 404 Not Found
     *  {
     *     code:0,
     *      msg:'失败或没有数据返回',
     *   }
     */
    public static function ratesurl($param){
        if (!isset($param['itemid']) || empty($param['itemid'])){
            return ['data' => '', 'code' => 0, 'msg' => '商品淘宝id未传'];
        }
        if (!isset($param['agent_id']) || empty($param['agent_id'])){
            $pid = 'mm_24757194_35528914_126340444'; //代理id未传则默认为平台所属会员
        }
        try{
                $url = 'http://v2.api.haodanku.com/ratesurl/apikey/shen';
                $arr['apikey'] = 'shen';
                $arr['itemid'] = $param['itemid'];
                $arr['pid'] = $pid;
                $arr['apikey'] = 'shen';
                $data = curl_request($url,$arr);
                if ($data['code'] == 1){
                    $info['coupon_click_url'] = $data['data']['coupon_click_url'];
                }else{
                    $info['coupon_click_url'] = '';
                }
            return ['code'=>200,'msg'=>'SUCCESS','data'=>$info];
        }catch (Exception $e){
            return ['code' => self::$err_code, 'msg' => $e->getMessage()];
        }
    }


    /**
     *
     * @apiGroup Goods
     * @apiVersion 1.0.2
     * @apiDescription 专题商品列表
     * @api {post} /goods.subject_item 专题商品列表
     * @apiName Goods_subject_item
     * @apiParam {int} subject_id 专题id
     * @apiParam {int} page 默认为1（这个需要在data外）
     *
     * @apiSuccess {int} code 结果码
     * @apiSuccess {String} msg 消息说明
     * @apiSuccess {Object} data
     * @apiSuccess {int} data.total 总数
     * @apiSuccess {String} data.per_page 每页数量
     * @apiSuccess {int} data.current_page 当前页
     * @apiSuccess {int} data.last_page 最后的页码
     * @apiSuccess {Object} data.data  商品数据
     * @apiSuccess {String} data.data.itemid 淘宝id
     * @apiSuccess {String} data.data.itemtitle 商品标题
     * @apiSuccess {String} data.data.itemshorttitle 商品短标题
     * @apiSuccess {String} data.data.itemprice 商品现价
     * @apiSuccess {String} data.data.itemendprice 商品券后价
     * @apiSuccess {String} data.data.itempic 商品图片
     * @apiSuccess {String} data.data.couponurl 优惠券链接
     * @apiSuccess {String} data.data.shoptype 店铺类型：天猫（B）C店（C）
     * @apiSuccess {int} data.data.itemsale 销量
     * @apiSuccess {String} data.data.couponmoney 优惠券金额
     * @apiSuccess {String} data.data.share_url 分享的链接
     * @apiSuccess {String} data.data.couponstarttime 优惠券开始
     * @apiSuccess {String} data.data.couponendtime 优惠券结束
     * @apiSuccessExample 成功示例
     *  HTTP/1.1 200 OK
     *  {
     *     code:200,
     *     msg:'success',
     *     data:{
    ...
     *	   }
     *  }
     *
     *  @apiError code 0 系统异常错误
     *  @apiError msg token已经过期
     *  @apiErrorExample {json} 失败示例
     *  HTTP/1.1 404 Not Found
     *  {
     *     code:0,
     *      msg:'失败或没有数据返回',
     *   }
     */
    public static function subject_item($param){
        if (!isset($param['subject_id']) || empty($param['subject_id'])){
            return ['data' => '', 'code' => 400001, 'msg' => '参数错误'];
        }
        try{
            $item_list = db('subject_items')->field('itemtitle,itemprice,itemshorttitle,itemid,itemsale,itemendprice,shoptype,couponmoney,couponurl,itempic,coupon,couponstarttime,couponendtime')->where(['subject_id'=>$param['subject_id']])->order('sort desc')->paginate('10');
            $item_list = $item_list->toArray();
            if (!empty($item_list['data'])){
                foreach ($item_list['data'] as $k=>$v){
                    $item_list['data'][$k]['itempic'] = get_img_url($v['itempic']);
                    $item_list['data'][$k]['share_url'] = '';
                }
            }
            return ['data' =>$item_list, 'code' => 200, 'msg' => 'success'];
        }catch (Exception $e){
            return ['data' =>'', 'code' => self::$err_code, 'msg' => $e->getMessage()];
        }
    }






}